import React, { useReducer, useContext, createContext } from 'react';

// 1-创建上下文空间
const NumContext = createContext();


function NumReducer(state, action){
    let newState = JSON.parse(JSON.stringify(state));
    switch (action.type) {
        case 'addNum':
            newState.num += action.value;
            break;
        default:
            break;
    }

    return newState;
}


function Son(){
    return (
        // 使用消费者
        <NumContext.Consumer>
            {
                ({state}) => <div>嘿嘿嘿{state.num}</div>
            }
        </NumContext.Consumer>
    )
}

function Btn(){
    return (
        // 使用消费者
        <NumContext.Consumer>
            {
                ({dispatch}) => <button onClick={ () => dispatch({ type: 'addNum', value: 1 }) } >累加</button>
            }
        </NumContext.Consumer>
    )
}


// useContext搭配useReducer实现react-redux
export default function UseReducerTest(){
    // useReducer:传入手写reducer方法和原始state返回新state和dispatch进行使用
    const [state, dispatch] = useReducer(NumReducer, { num: 0});

    return (
        <div>
            {/* 2-上下文空间传参，传参对象为useReducer的返参 */}
            {/* 使用提供者 */}
            <NumContext.Provider value={{state, dispatch}}>
                <Son />
                <Btn />
            </NumContext.Provider>
        </div>
    )
}